package com.atwu.wl2022.controller;

import com.atwu.wl2022.entity.User;
import com.atwu.wl2022.service.IArticleService;
import com.atwu.wl2022.service.IUserService;
import com.atwu.wl2022.util.RedisKeyUtils;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

/**
 * 用户登录之后才能使用的功能
 *
 * @author wulejay
 */
@Controller
@RequestMapping("/user")
@Slf4j
class UserController {

	@Autowired
	IArticleService iArticleService;

	@Autowired
	IUserService iUserService;

	@Autowired
	RedisTemplate<String, Object> redisTemplate;

	/**
	 * 点赞逻辑
	 *
	 * @param userId    点赞用户id
	 * @param articleId 被点赞文章id
	 * @return 点赞成功与否
	 */
	@GetMapping("/setLike")
	@ResponseBody
	public Boolean serLike(String userId, String articleId) {
		String key = RedisKeyUtils.getLikedKey(articleId, userId);
		//记录某文章总数的缓存
		Integer postArticle = (Integer) redisTemplate.boundHashOps("HashKey").get("POST_ARTICLE:" + articleId);
		//记录用户点赞的缓存
		Integer keyValue = (Integer) redisTemplate.boundHashOps("HashKey").get(key);
		/*
		 * 首先，看redis有没有key为key的值，{
		 *     有：说明该用户已点赞，再查一下，redis有没有该文章的点赞总数缓存{
		 *         有：说明该文章点赞总数的缓存已经创建出来了
		 *          只要把key为"POST_ARTICLE:" + articleId的值减一
		 *          再把key为key的缓存删掉
		 *          return false；
		 *     }
		 * }else{
		 *     没有：说明该用户对该文章还没点赞过，再查一下，redis有没有该文章的点赞总数缓存{
		 *         有：说明该文章点赞总数的缓存已经创建出来了
		 *         只要把key为"POST_ARTICLE:" + articleId的值加1；
		 *          再创建一个 key为key ，value为1的缓存
		 *          return true;
		 *     }else{
		 *         没有：说明，该文章点赞总数的缓存还没创建出来
		 *                  创建一个值为1的
		 *          再创建一个 key为key ，value为1的缓存
		 *          return true;
		 *     }
		 * }
		 */
		if (keyValue != null) {
			redisTemplate.opsForHash().put("HashKey", "POST_ARTICLE:" + articleId, postArticle - 1);
			redisTemplate.opsForHash().delete("HashKey", key);
			return false;
		} else {
			if (postArticle != null) {
				redisTemplate.opsForHash().put("HashKey", "POST_ARTICLE:" + articleId, postArticle + 1);
			} else {
				redisTemplate.boundHashOps("HashKey").put("POST_ARTICLE:" + articleId, 1);
			}
			redisTemplate.boundHashOps("HashKey").put(key, 1);
			return true;
		}
	}


	/**
	 * 注销
	 *
	 * @param session 域对象
	 * @return 回首页
	 */
	@GetMapping("/logOut")
	public String logOut(HttpSession session) {
		//注销之后，回到首页，清空session中信息
		session.removeAttribute("image");
		session.removeAttribute("userName");
		session.removeAttribute("identity");
		session.removeAttribute("nickName");
		session.removeAttribute("loginUserId");
		session.removeAttribute("email");
		return "redirect:/index";
	}


	/**
	 * 去后台个人信息页
	 *
	 * @return 页面地址
	 */
	@GetMapping("/toPersonalInformation")
	public String toUserAdmin() {
		log.info("跳转到用户设置页面");
		return "user/personalInformation";
	}

	@PostMapping("/save2")
	public String  save2(@RequestParam("nickName")  String nickName,@RequestParam("email")   String email ,HttpSession session) {
//		修改个人信息
		log.info("接收到的昵称为：{}，邮箱为：{}",nickName,email);
		Integer loginUserId = (Integer) session.getAttribute("loginUserId");
		iUserService.update(new UpdateWrapper<User>().eq("id",loginUserId).set("nick_name",nickName).set("Email",email));
		session.setAttribute("email",email);
		session.setAttribute("nickName",nickName);
		return "user/personalInformation::visit";
	}
	@PostMapping("/save")
	public String  save(@RequestPart("image")MultipartFile image , @RequestParam("nickName")  String nickName,@RequestParam("email")   String email ,HttpSession session) throws IOException {
//		修改个人信息附加修改头像
		log.info("接收到的昵称为：{},邮箱为：{},头像为{}",nickName,email,image.getOriginalFilename());

			//先判断有没有原来的头像（用户id+图片名）
				//有：删除
				//没有：上传（图片名为用户id+图片名）
		File path = new File(ResourceUtils.getURL("classpath:").getPath());
		if(!path.exists()) {
			path = new File("");
		}
		File upload = new File(path.getAbsolutePath(),"static/image/userImage");
		if(!upload.exists()) {
			upload.mkdirs();
		}
		String parent= upload.getPath();
		log.info("头像图片上传路径:{}",parent);
		Integer userId = (Integer)session.getAttribute("loginUserId");
		Object userImage = session.getAttribute("image");
		String s = parent + "\\"+userId+"-"+userImage;
		log.info("上一个头像文件地址:{}",s);
		File dir = new File(s);
		if(dir.exists()){
			log.info("图像文件已存在");
			dir.delete();//删除文件
		}
		//上传图片到该地址
		//1、获取接收的图片名
		String filename = image.getOriginalFilename();
		//2、新的文件名字，防止存入重名地址
		String newFileName = userId+"-"+ filename;
		//3、封装上传文件位置的全路径
		File targetFile = new File(parent, newFileName);
		//4、把图片上传到封装上传文件位置的全路径
		image.transferTo(targetFile);
		log.info("存入的图片名为：{}", newFileName);
		iUserService.update(new UpdateWrapper<User>().eq("id",userId).set("nick_name",nickName).set("Email",email).set("image",newFileName));
		session.setAttribute("email",email);
		session.setAttribute("image",newFileName);
		session.setAttribute("nickName",nickName);
		return "user/personalInformation::visit";
	}



	@PostMapping("/updatePwd")
	@ResponseBody
	public Boolean updatePwd(@RequestParam("oldPwd") String oldPwd,@RequestParam("newPwd") String newPwd,HttpSession session){
		Integer userId = (Integer)session.getAttribute("loginUserId");
		User user = iUserService.getById(userId);
		String password = user.getPassword();
		if(oldPwd.equals(password)){
			//验证成功
			iUserService.update(new UpdateWrapper<User>().eq("id",userId).set("password",newPwd));
			return true;
		}else {
			//验证失败
			return false;
		}
	}

	/**
	 * 去后台修改密码页
	 *
	 * @return 修改密码页地址
	 */
	@GetMapping("/changePassword")
	public String toChangePassword() {
		return "user/changePassword";
	}

}
